package 尚硅谷;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author zhangmin
 * @create 2022-03-24 14:28
 * 线程池
 * 使用线程
 * 1、实现Runnable接口
 * 2、实现Callable接口：带返回值的
 */
class MyThread implements Runnable{

    @Override
    public void run() {

    }
}

class MyThread2 implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println("come in callable");
        return 1024;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //Thread thread=new Thread(new MyThread());

        //用实现Callable接口的线程类来new一个FutureTask
        FutureTask<Integer> futureTask=new FutureTask<>(new MyThread2());
        new Thread(futureTask,"AA").start();
        new Thread(futureTask,"BB").start();//这里不会再去计算一次

        System.out.println("返回值："+futureTask.get());//使用get来获得结果，get建议放在最后

        //方法2，使用自旋
/*        while (!futureTask.isDone()){

        }*/
    }
}
